package com.aims.server.service.impl;

import com.aims.server.common.ErrorCode;
import com.aims.server.common.util.ExtAccountWordExporter;
import com.aims.server.common.util.ExtAccountWordExporterV2;
import com.aims.server.dao.ExtAccountFormMapper;
import com.aims.server.dao.ExtAccountItemMapper;
import com.aims.server.dto.ExtAccountFormDTO;
import com.aims.server.dto.ExtAccountItemDTO;
import com.aims.server.entity.ExtAccountForm;
import com.aims.server.entity.ExtAccountItem;
import com.aims.server.service.ExtAccountFormService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 企业或集团外常用账户信息表Service实现
 */
@Service
public class ExtAccountFormServiceImpl implements ExtAccountFormService {
    @Resource
    private ExtAccountFormMapper formMapper;

    @Resource
    private ExtAccountItemMapper itemMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createForm(ExtAccountFormDTO dto) {
        // 生成UUID作为formId
        String formId = UUID.randomUUID().toString();

        // 构建表单抬头对象
        ExtAccountForm form = new ExtAccountForm();
        BeanUtils.copyProperties(dto, form);
        form.setFormId(formId);
        form.setCreatedAt(LocalDateTime.now());
        form.setUpdatedAt(LocalDateTime.now());

        // 插入抬头
        formMapper.insert(form);

        // 插入明细
        if (dto.getItems() != null && !dto.getItems().isEmpty()) {
            List<ExtAccountItem> items = new ArrayList<>();
            for (ExtAccountItemDTO itemDTO : dto.getItems()) {
                ExtAccountItem item = new ExtAccountItem();
                BeanUtils.copyProperties(itemDTO, item);
                item.setItemId(UUID.randomUUID().toString());
                item.setFormId(formId);
                items.add(item);
            }
            itemMapper.batchInsert(items);
        }

        return formId;
    }

    @Override
    public ExtAccountForm getFormById(String formId) {
        ExtAccountForm form = formMapper.selectByFormId(formId);
        if (form == null) {
            throw new RuntimeException(ErrorCode.FORM_NOT_FOUND.getMessage());
        }

        // 查询关联明细
        List<ExtAccountItem> items = itemMapper.selectByFormId(formId);
        form.setItems(items);

        return form;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateForm(String formId, ExtAccountFormDTO dto) {
        // 检查表单是否存在
        ExtAccountForm existForm = formMapper.selectByFormId(formId);
        if (existForm == null) {
            throw new RuntimeException(ErrorCode.FORM_NOT_FOUND.getMessage());
        }

        // 更新表单抬头
        ExtAccountForm form = new ExtAccountForm();
        BeanUtils.copyProperties(dto, form);
        form.setFormId(formId);
        form.setUpdatedAt(LocalDateTime.now());
        formMapper.updateByFormId(form);

        // 删除旧明细
        itemMapper.deleteByFormId(formId);

        // 插入新明细
        if (dto.getItems() != null && !dto.getItems().isEmpty()) {
            List<ExtAccountItem> items = new ArrayList<>();
            for (ExtAccountItemDTO itemDTO : dto.getItems()) {
                ExtAccountItem item = new ExtAccountItem();
                BeanUtils.copyProperties(itemDTO, item);
                item.setItemId(UUID.randomUUID().toString());
                item.setFormId(formId);
                items.add(item);
            }
            itemMapper.batchInsert(items);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteForm(String formId) {
        // 检查表单是否存在
        ExtAccountForm form = formMapper.selectByFormId(formId);
        if (form == null) {
            throw new RuntimeException(ErrorCode.FORM_NOT_FOUND.getMessage());
        }

        // 删除明细(外键级联删除,这里显式调用以确保)
        itemMapper.deleteByFormId(formId);

        // 删除抬头
        formMapper.deleteByFormId(formId);
    }

    @Override
    public Map<String, Object> getFormList(String companyName, String mainApplyingAccount,
                                          String contactPhone, Integer page, Integer size) {
        // 参数校验
        if (page == null || page < 1) {
            page = 1;
        }
        if (size == null || size < 1) {
            size = 10;
        }

        // 计算偏移量
        int offset = (page - 1) * size;

        // 查询列表
        List<ExtAccountForm> list = formMapper.selectPageList(companyName, mainApplyingAccount,
                contactPhone, offset, size);

        // 查询总数
        int total = formMapper.selectCount(companyName, mainApplyingAccount, contactPhone);

        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("list", list);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        result.put("totalPages", (total + size - 1) / size);

        return result;
    }

    @Override
    public List<ExtAccountItem> getItemsByFormId(String formId) {
        // 检查表单是否存在
        ExtAccountForm form = formMapper.selectByFormId(formId);
        if (form == null) {
            throw new RuntimeException(ErrorCode.FORM_NOT_FOUND.getMessage());
        }

        return itemMapper.selectByFormId(formId);
    }

    @Override
    public byte[] exportFormToWord(String formId) {
        // 查询表单数据(含明细)
        ExtAccountForm form = getFormById(formId);

        try {
            // 使用工具类导出Word文档
            return ExtAccountWordExporter.exportToWord(form);
        } catch (IOException e) {
            throw new RuntimeException("导出Word文档失败: " + e.getMessage(), e);
        }
    }

    @Override
    public byte[] exportFormToWordV2(String formId) {
        // 查询表单数据(含明细)
        ExtAccountForm form = getFormById(formId);

        try {
            // 使用V2工具类导出Word文档（新格式）
            return ExtAccountWordExporterV2.exportToWord(form);
        } catch (IOException e) {
            throw new RuntimeException("导出Word文档失败(V2): " + e.getMessage(), e);
        }
    }
}